#!/bin/bash

# Web Notes 重新部署脚本
set -e

echo "🚀 开始重新部署 Web Notes..."

# 配置
PROJECT_DIR="/var/www/web-notes"
WEB_ROOT="/var/www/html"
BACKUP_DIR="/var/www/backups"

# 创建备份目录
sudo mkdir -p $BACKUP_DIR

echo "📦 停止当前服务..."
pm2 stop all || true
pm2 delete all || true

echo "📁 进入项目目录..."
cd $PROJECT_DIR

echo "🔨 重新构建后端..."
cd web-notes-backend
npm install
npm run build

echo "🎨 重新构建前端..."
cd ../web-notes-frontend
npm install
npm run build

echo "💾 备份当前前端文件..."
sudo cp -r $WEB_ROOT $BACKUP_DIR/html.backup.$(date +%Y%m%d_%H%M%S)

echo "📤 部署新的前端文件..."
sudo rm -rf $WEB_ROOT/*
sudo cp -r dist/* $WEB_ROOT/
sudo chown -R www-data:www-data $WEB_ROOT/
sudo chmod -R 755 $WEB_ROOT/

echo "🚀 启动后端服务..."
cd ../web-notes-backend
pm2 start dist/index.js --name "web-notes-api"

echo "⏳ 等待服务启动..."
sleep 5

echo "🔍 验证部署..."
echo "PM2 状态:"
pm2 status

echo "后端健康检查:"
curl -s http://127.0.0.1:3000/health || echo "❌ 后端连接失败"

echo "端口监听状态:"
netstat -tlnp | grep :3000 || echo "❌ 端口3000未监听"

echo "✅ 重新部署完成！"
echo "🌐 请访问您的网站测试功能"
echo "📋 查看日志: pm2 logs web-notes-api"